package ProxyDynamic;

import proxyStatic.Study;
import proxyStatic.Student;
import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;

/*
 * 项目名:    JavaProxy
 * 包名       ProxyDynamic
 * 文件名:    ProxyDynamicTest
 * 创建者:    ZJB
 * 创建时间:  2017/10/26 on 16:18
 * 描述:     TODO
 */
public class ProxyDynamicTest {
    public static void main(String[] args) {
        Student student = new Student();
        generateClassFile(student.getClass(), "aaa");
        Object object = Proxy.newProxyInstance(student.getClass().getClassLoader(),
                student.getClass().getInterfaces(),
                new ProxyHandler(student));
        Study study = (Study) object;
        study.doHomeWork();
    }

    public static void generateClassFile(Class clazz, String proxyName) {
        //根据类信息和提供的代理类名称，生成字节码
        byte[] classFile = ProxyGenerator.generateProxyClass(proxyName, clazz.getInterfaces());
        String paths = clazz.getResource(".").getPath();
        System.out.println(paths);
        FileOutputStream out = null;

        try {
            //保留到硬盘中
            out = new FileOutputStream(paths + proxyName + ".class");
            out.write(classFile);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
